#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/system/error_code.hpp>
#include <boost/bind/bind.hpp>

class IPCServer {
public:
    IPCServer();
    ~IPCServer();
    bool run();

private:
    void accept_handler(const boost::system::error_code& ec, const boost::shared_ptr<boost::asio::ip::tcp::socket>& sock);
    bool accept();
    void write_handler(const boost::system::error_code&ec);
    bool initAsync();
    bool send();
    bool recv();

private:
    boost::asio::io_service m_io;
    boost::asio::ip::tcp::acceptor m_acceptor;
};
using namespace std;
using namespace boost::asio;
typedef ip::tcp::endpoint endpoint_type;
typedef ip::tcp::socket socket_type;
typedef boost::shared_ptr<socket_type> sock_ptr;


IPCServer::IPCServer():m_acceptor(m_io, endpoint_type (ip::tcp::v4(), 1090)) {
    accept();
}

bool IPCServer::accept() {
    cout << "正在监听：" << m_acceptor.local_endpoint().address() << ":" << m_acceptor.local_endpoint().port() << endl;
    sock_ptr sock(new socket_type(m_io));
    m_acceptor.async_accept(*sock, boost::bind(&IPCServer::accept_handler, this, boost::asio::placeholders::error, sock));
    return true;
}

void IPCServer::accept_handler(const boost::system::error_code& ec, const sock_ptr& sock) {
    if (ec){
        cout << "异步接收错误！请检查配置" << endl;
        return;
    }
    cout << "客户端：";
    cout<<sock->remote_endpoint().address() << ":" << sock->remote_endpoint().port() <<endl;
    sock->async_write_some(buffer("这是从服务端发送过来的异步消息！"), boost::bind(&IPCServer::write_handler, this, boost::asio::placeholders::error));
}

void IPCServer::write_handler(const boost::system::error_code&ec)
{
    if (ec) {
        cout << "异步写入错误！请检查配置" << endl;
    }
    cout<<"消息发送完毕"<<endl;
}

IPCServer::~IPCServer() = default;

bool IPCServer::send() {
    return false;
}

bool IPCServer::recv() {
    return false;
}

bool IPCServer::initAsync() {
    return true;
}

bool IPCServer::run() {
    m_io.run();
    return true;
}
int main(int argc,char** argv){
    IPCServer ipcServer;
    ipcServer.run();
//    while (true){};
    return 0;
}